#### REPLICATION FILE ANALYSES IN SUPPLEMENTARY MATERIALS ####
#### SETUP ####
## Packages
library(tidyverse) # workflow
library(haven) # Stata-like labels
library(DeclareDesign) # Tidyverse-friendly t-test
library(infer) # Tidyverse-friendly chi-square test
library(here) # relative path management
library(nnet) # multinomial logit

## Data
load(here("credit.rda"))

## Recoding
# Create categories for treatment groups
credit = credit %>% mutate(naming = ifelse(name == 1, "Labeled", "Not Labeled"),
                           mayor = ifelse(male_mayor == 1, "Man mayor", "Woman mayor"),
                           bias = recode(particularism,
                                         "No" = "Unbiased",
                                         "Omit" = "No_info",
                                         "Yes" = "Biased"))

# arrange variables in logical order
credit$mayor = fct_relevel(credit$mayor, "Man mayor", "Woman mayor")

#### CUSTOM FUNCTION TO MAKE TABLES WITH MEANS AND DIFFERENCES IN MEANS ####
# Function grabs a column and prints a data frame like the one Matt did
# Prioritizing vertical space to facilitate visualizing

make_tab_df = function(varname, data){
  temp = data
  
  temp$x = pull(data, varname)
  
  # core table of means
  means = temp %>% 
    select(mayor, bias, x) %>% 
    group_by(mayor, bias) %>% 
    summarize(mu = mean(x, na.rm = TRUE),
              sd = sd(x, na.rm = TRUE),
              p = t.test(x)$p.value) %>% 
    mutate(outcome = varname,
           mean = paste(sprintf("%.2f", mu),
                        sprintf("(%.2f)", sd),
                        sprintf("[%.2f]", p))) %>% 
    select(outcome, mayor, bias, mean) %>% 
    pivot_wider(names_from = "bias", values_from = mean)
  
  # side table of differences in implementation
  biased_noinfo = temp %>% 
    filter(bias != "Unbiased") %>% 
    select(mayor, biased, x) %>% 
    group_by(mayor) %>% 
    group_split() %>% 
    map(~difference_in_means(x ~ biased, data = .)) %>% 
    map(tidy) %>% 
    bind_rows() %>% 
    mutate(Biased_v_NoInfo = paste(sprintf("%.2f", estimate),
                                   sprintf("(%.2f)", std.error),
                                   sprintf("[%.2f]", p.value))) %>% 
    select(Biased_v_NoInfo)
  
  unbiased_noinfo = temp %>% 
    filter(bias != "Biased") %>% 
    select(mayor, unbiased, x) %>% 
    group_by(mayor) %>% 
    group_split() %>% 
    map(~difference_in_means(x ~ unbiased, data = .)) %>% 
    map(tidy) %>% 
    bind_rows() %>% 
    mutate(Unbiased_v_NoInfo = paste(sprintf("%.2f", estimate),
                                     sprintf("(%.2f)", std.error),
                                     sprintf("[%.2f]", p.value))) %>% 
    select(Unbiased_v_NoInfo)
  
  unbiased_biased = temp %>% 
    filter(bias != "No_info") %>% 
    select(mayor, unbiased, x) %>% 
    group_by(mayor) %>% 
    group_split() %>% 
    map(~difference_in_means(x ~ unbiased, data = .)) %>% 
    map(tidy) %>% 
    bind_rows() %>% 
    mutate(Unbiased_v_Biased = paste(sprintf("%.2f", estimate),
                                     sprintf("(%.2f)", std.error),
                                     sprintf("[%.2f]", p.value))) %>% 
    select(Unbiased_v_Biased)
  
  hdiffs = cbind(means, biased_noinfo, unbiased_noinfo, unbiased_biased)
  
  # bottom table of differences in gender
  vlabs = temp %>% 
    arrange(bias) %>% 
    group_by(bias) %>% 
    summarize(n = n()) %>% 
    select(!n)
  
  veffs = temp %>% 
    select(bias, male_mayor, x) %>%
    arrange(bias) %>% 
    group_by(bias)%>% 
    group_split() %>% 
    map(~difference_in_means(x ~ male_mayor, data = .)) %>% 
    map(tidy) %>% 
    bind_rows() %>% 
    mutate(diff = paste(sprintf("%.2f", estimate),
                        sprintf("(%.2f)", std.error),
                        sprintf("[%.2f]", p.value))) %>% 
    select(diff)
  
  # difference in differences by gender
  vdnds = rbind(
    tidy(lm_robust(x ~ biased*male_mayor, 
                   data = temp, 
                   subset = bias != "Unbiased")),
    tidy(lm_robust(x ~ unbiased*male_mayor, 
                   data = temp,
                   subset = bias != "Biased")),
    tidy(lm_robust(x ~ unbiased*male_mayor, 
                   data = temp,
                   subset = bias != "No_info"))
  ) %>% 
    filter(grepl(":", term)) %>% 
    mutate(diff = paste(sprintf("%.2f", estimate),
                        sprintf("(%.2f)", std.error),
                        sprintf("[%.2f]", p.value))) %>% 
    select(diff)
  
  
  vdiffs = data.frame(
    bias = c(vlabs$bias,"Biased_v_NoInfo", "Unbiased_v_NoInfo",
             "Unbiased_v_Biased"),
    diff = c(veffs$diff, vdnds$diff)
  ) %>% 
    pivot_wider(names_from = "bias", values_from = "diff") %>% 
    mutate(outcome = varname, mayor = "Difference") %>% 
    select(outcome, mayor, Biased, No_info, Unbiased,
           Biased_v_NoInfo, Unbiased_v_NoInfo, Unbiased_v_Biased)
  
  tab = rbind(hdiffs, vdiffs)
  
  
  return(tab)
}

#### A. RESULTS TABLES ####
## A1
voting = c("vote_respond", "help_reelect", "vote_benefic") 

voting_tab = voting %>% 
  map(~ make_tab_df(.x, credit)) %>% 
  bind_rows()

voting_tab$outcome = recode(voting_tab$outcome,
                            "vote_respond" = "Incumbent vote",
                            "help_reelect" = "Help reelection",
                            "vote_benefic" = "Beneficiaries vote")

colnames(voting_tab) = c("Outcome", "Mayor", "Biased", "No info", "Unbiased",
                         "Biased - No info", "Unbiased - No info", 
                         "Unbiased - Biased")

voting_tab

## A2
control = credit %>% filter(bias == "No_info")

dim = c("mayor_corrupt", "mayor_patron", "mayor_buyvotes") %>% 
  map(~ formula(paste0(. , "~ mayor"))) %>% 
  map(~ difference_in_means(., data = control)) %>% 
  map(tidy) %>% 
  bind_rows() %>% 
  select(outcome, diff_means = estimate, p.value)


# chi-square
control$mayor_corrupt_f = factor(control$mayor_corrupt)
control$mayor_patron_f = factor(control$mayor_patron)
control$mayor_buyvotes_f = factor(control$mayor_buyvotes)

chi = rbind(
  chisq_test(mayor_corrupt_f ~ mayor, x = control) %>% mutate(outcome = "mayor_corrupt"),
  chisq_test(mayor_patron_f ~ mayor, x = control) %>% mutate(outcome = "mayor_patron"),
  chisq_test(mayor_buyvotes_f ~ mayor, x = control) %>% mutate(outcome = "mayor_buyvotes")
) %>% 
  rename(chisq = statistic)

# Now make means
means = control %>% 
  group_by(mayor) %>% 
  summarize(mayor_corrupt = mean(mayor_corrupt, na.rm = TRUE),
            mayor_patron = mean(mayor_patron, na.rm = TRUE),
            mayor_buyvotes = mean(mayor_buyvotes, na.rm = TRUE)) %>% 
  pivot_longer(cols = c("mayor_corrupt", "mayor_patron", "mayor_buyvotes"),
               names_to = "outcome", values_to = "mean") %>% 
  pivot_wider(names_from = "mayor", values_from = "mean")

# merge
low_exp_tab = merge(means, dim, by = "outcome")

low_exp_tab = merge(low_exp_tab, chi, by = "outcome")

low_exp_tab

## A3
program = c("satisfy_respond", "distrib_unbiased") 

program_tab = program %>%
  map(~ make_tab_df(.x, credit)) %>% 
  bind_rows()

program_tab$outcome = recode(program_tab$outcome,
                             "distrib_unbiased" = "Unbiased distribution", 
                             "satisfy_respond" = "Satisfy respondent")

colnames(program_tab) = c("Outcome", "Mayor", "Biased", "No info", "Unbiased",
                          "Biased - No info", "Unbiased - No info", 
                          "Unbiased - Biased")

program_tab

#### B. ADDITIONAL RESULTS ####
## B1
# Treatment combinations
credit$treatment2 = paste(credit$mayor, credit$bias, sep = "-")

credit$treatment2 = fct_relevel(credit$treatment2, 
                                "Man mayor-No_info", 
                                "Man mayor-Biased",
                                "Man mayor-Unbiased",
                                "Woman mayor-No_info", 
                                "Woman mayor-Biased",
                                "Woman mayor-Unbiased")

# Multinomial logit
bal = multinom(treatment2 ~ age + hhh_edu + poor + sex, data = credit)

summary(bal)

balance = tidy(bal) %>% 
  mutate(term = recode(term,
                       "(Intercept)" = "Intercept",
                       "age" = "Age",
                       "hhh_edu" = "Education",
                       "poor" = "Poor",
                       "sexMale" = "Sex = Man"),
         Mayor = ifelse(str_detect(y.level, "woman"), "Woman", "Man"),
         Implementation = gsub(x = y.level, "^.*?-", ""),
         Implementation = str_replace(Implementation, "_", " ")) %>% 
  select(Mayor, Implementation, Term = term, Estimate = estimate,
         SE = std.error, `p_value` = p.value)

balance 

## B2
pmayor = c("mayor_patron", "mayor_buyvotes", "mayor_corrupt")

pmayor_tab = pmayor %>%
  map(~ make_tab_df(.x, credit)) %>%
  bind_rows()

pmayor_tab$outcome = recode(pmayor_tab$outcome,
                            "mayor_patron" = "Patronage",
                            "mayor_buyvotes" = "Vote buying",
                            "mayor_corrupt" = "Corruption")

colnames(pmayor_tab) = c("Outcome", "Mayor", "Biased", "No info", "Unbiased",
                         "Biased - No info", "Unbiased - No info",
                         "Unbiased - Biased")


pmayor_tab


## B3
credit_m = credit %>% filter(sex == "Male")
credit_f = credit %>% filter(sex == "Female")

# Voting outcomes
voting_gender = rbind(
  voting %>%
    map( ~ make_tab_df(.x, credit_m)) %>%
    bind_rows() %>%
    mutate(respondent = "Man respondent"),
  voting %>% 
    map( ~ make_tab_df(.x, credit_f)) %>%
    bind_rows() %>%
    mutate(respondent = "Woman respondent")
) %>% 
  relocate(outcome, respondent) %>% 
  arrange(outcome, respondent)

voting_gender$respondent = fct_relevel(voting_gender$respondent,
                                       "Man respondent",
                                       "Woman respondent")

voting_gender$outcome = recode(voting_gender$outcome,
                               "vote_respond" = "Incumbent vote",
                               "help_reelect" = "Help reelection")

colnames(voting_gender) = c("Outcome", "Respondent", "Mayor", "Biased",
                            "No info", "Unbiased",
                            "Biased - No info", "Unbiased - No info", 
                            "Unbiased - Biased")

# Program perception outcomes
program_gender = rbind(
  program %>%
    map( ~ make_tab_df(.x, credit_m)) %>%
    bind_rows() %>%
    mutate(respondent = "Man respondent"),
  program %>% 
    map( ~ make_tab_df(.x, credit_f)) %>%
    bind_rows() %>%
    mutate(respondent = "Woman respondent")
) %>% 
  relocate(outcome, respondent) %>% 
  arrange(outcome, respondent)


program_gender$respondent = fct_relevel(program_gender$respondent,
                                        "Man respondent",
                                        "Woman respondent")

program_gender$outcome = recode(program_gender$outcome,
                                "distrib_unbiased" = "Unbiased distribution",
                                "satisfy_respond" = "Satisfy respondent")

colnames(program_gender) = c("Outcome", "Respondent", "Mayor", "Biased",
                             "No info", "Unbiased",
                             "Biased - No info", "Unbiased - No info", 
                             "Unbiased - Biased")

voting_gender
program_gender

## B4
credit_poor = credit %>% filter(poor == 1)
credit_rich = credit %>% filter(poor == 0)

out = c(voting, program)

social_class = rbind(
  out %>% 
    map(~ make_tab_df(.x, credit_poor)) %>% 
    bind_rows() %>% 
    mutate(respondent = "Lower class"),
  out %>% 
    map(~ make_tab_df(.x, credit_rich)) %>% 
    bind_rows() %>% 
    mutate(respondent = "Upper/middle class")
) %>% 
  relocate(outcome, respondent) %>% 
  mutate(outcome = factor(outcome, levels = out),
         mayor = str_remove(mayor, " mayor")) %>% 
  group_by(outcome) %>% 
  arrange(respondent, .by_group = TRUE) %>% 
  ungroup() 

social_class

## B5
credit_copar = credit %>% filter(partisan_match_control == 1)
credit_nopar = credit %>% filter(partisan_match_control == 0)

copartisanship = rbind(
  out %>% 
    map(~ make_tab_df(.x, credit_copar)) %>% 
    bind_rows() %>% 
    mutate(copartisan = "Yes"),
  out %>% 
    map(~ make_tab_df(.x, credit_nopar)) %>% 
    bind_rows() %>% 
    mutate(copartisan = "No")
) %>% 
  relocate(outcome, copartisan) %>% 
  mutate(outcome = factor(outcome, levels = out),
         mayor = str_remove(mayor, " mayor")) %>% 
  group_by(outcome) %>% 
  arrange(copartisan, .by_group = TRUE) %>% 
  ungroup()

copartisanship

## B6
credit = credit %>% 
  mutate(recall_gender_correct = ifelse(
    mayor == "Man mayor" & recall_gender == 1 |
      mayor == "Woman mayor" & recall_gender == 2,
    1, 0))

credit$naming = fct_relevel(credit$naming, "Labeled", after = Inf)

recall_picture = lm_robust(recall_gender_correct ~ mayor * naming,
                           data = credit,
                           se_type = "stata")

recall_picture_tab = tidy(recall_picture) %>% 
  mutate(term = recode(term,
                       "(Intercept)" = "Intercept (Man mayor-Not labeled)",
                       "mayorWoman mayor" = "Woman mayor",
                       "namingLabeled" = "Labeled",
                       "mayorWoman mayor:namingLabeled"= "Interaction")) %>% 
  select(Term = term, Estimate = estimate, SE = std.error, p.value)

summary(recall_picture)
recall_picture_tab # as labeled in appendix

## B7
credit = credit %>% 
  mutate(recall_gender_misremember = ifelse(
    mayor == "Man mayor" & recall_gender == 2 |
      mayor == "Woman mayor" & recall_gender == 1,
    1, 0))

# check
table(credit$recall_gender_misremember)

credit_no_misremember = credit %>% 
  filter(recall_gender_misremember == 0)

misremember = out %>% 
  map(~ make_tab_df(.x, credit_no_misremember)) %>% 
  bind_rows()

misremember

## B8
# Small tweak to have no info as baseline category
credit$bias = fct_relevel(credit$bias,
                          "No_info",
                          "Biased",
                          "Unbiased")

# Baseline models
b_vote_f = lm_robust(vote_respond ~ bias,
                     data = credit,
                     se_type = "stata",
                     subset = mayor == "Woman mayor")

b_win_f = lm_robust(help_reelect ~ bias,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Woman mayor")

b_sat_f = lm_robust(satisfy_respond ~ bias,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Woman mayor")

b_unb_f = lm_robust(distrib_unbiased ~ bias,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Man mayor")

b_vote_m = lm_robust(vote_respond ~ bias,
                     data = credit,
                     se_type = "stata",
                     subset = mayor == "Man mayor")

b_win_m = lm_robust(help_reelect ~ bias,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Man mayor")

b_sat_m = lm_robust(satisfy_respond ~ bias,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Man mayor")

b_unb_m = lm_robust(distrib_unbiased ~ bias,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Man mayor")


# Long models
l_vote_f = lm_robust(vote_respond ~ bias + name + party + 
                       hhh_edu,
                     data = credit,
                     se_type = "stata",
                     subset = mayor == "Woman mayor")

l_win_f = lm_robust(help_reelect ~ bias + name + party + 
                      hhh_edu,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Woman mayor")

l_sat_f = lm_robust(satisfy_respond ~ bias + name + party +
                      hhh_edu,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Woman mayor")

l_unb_f = lm_robust(distrib_unbiased ~ bias + name + party +
                      hhh_edu,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Man mayor")

l_vote_m = lm_robust(vote_respond ~ bias + name + party + 
                       hhh_edu,
                     data = credit,
                     se_type = "stata",
                     subset = mayor == "Man mayor")

l_win_m = lm_robust(help_reelect ~ bias + name + party + 
                      hhh_edu,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Man mayor")

l_sat_m = lm_robust(satisfy_respond ~ bias + name + party +
                      hhh_edu,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Man mayor")

l_unb_m = lm_robust(distrib_unbiased ~ bias + name + party +
                      hhh_edu,
                    data = credit,
                    se_type = "stata",
                    subset = mayor == "Man mayor")

# See results
summary(b_vote_f)
summary(b_win_f)
summary(b_sat_f)
summary(b_unb_f)
summary(b_vote_m)
summary(b_win_m)
summary(b_sat_m)
summary(b_unb_m)
summary(l_vote_f)
summary(l_win_f)
summary(l_sat_f)
summary(l_unb_f)
summary(l_vote_m)
summary(l_win_m)
summary(l_sat_m)
summary(l_unb_m)


## B9
program_manip_0 = lm_robust(distrib_unbiased ~ bias,
                            data = credit,
                            se_type = "stata")

program_manip_1 = lm_robust(distrib_unbiased ~ bias + mayor + 
                              name + party,
                            data = credit,
                            se_type = "stata")

summary(program_manip_0)
summary(program_manip_1)

## B10
cop_vote = lm_robust(vote_respond ~ partisan_match_control + bias + mayor + 
                       name + hhh_edu,
                     data = credit,
                     se_type = "stata")

cop_help = lm_robust(help_reelect ~ partisan_match_control + bias + mayor + 
                       name + hhh_edu,
                     data = credit,
                     se_type = "stata")

cop_satr = lm_robust(satisfy_respond ~ partisan_match_control + bias + mayor + 
                       name + hhh_edu,
                     data = credit,
                     se_type = "stata")

cop_dstr = lm_robust(distrib_unbiased ~ partisan_match_control + bias + mayor + 
                       name + hhh_edu,
                     data = credit,
                     se_type = "stata")

summary(cop_vote)
summary(cop_help)
summary(cop_satr)
summary(cop_dstr)

## B11
# Need to reload data because previous recoding breaks the custom function
load(here("credit.rda"))
credit = credit %>% mutate(naming = ifelse(name == 1, "Labeled", "Not Labeled"),
                           mayor = ifelse(male_mayor == 1, "Man mayor", "Woman mayor"),
                           bias = recode(particularism,
                                         "No" = "Unbiased",
                                         "Omit" = "No_info",
                                         "Yes" = "Biased"))

# arrange variables in logical order
credit$mayor = fct_relevel(credit$mayor, "Man mayor", "Woman mayor")

# Now apply
idea = c("mayor_idea_vecinos", "mayor_idea_respond")

idea_tab = idea %>%
  map(~ make_tab_df(.x, credit)) %>%
  bind_rows()

idea_tab$outcome = recode(idea_tab$outcome,
                          "mayor_idea_vecinos" = "Neighbors",
                          "mayor_idea_respond" = "Respondent")

colnames(idea_tab) = c("Outcome", "Mayor", "Biased", "No info", "Unbiased",
                       "Biased - No info", "Unbiased - No info",
                       "Unbiased - Biased")


idea_tab

#### C. STUDY DETAILS ####
## Table C1 was based on summary statistics reported by survey firm, no data was collected directly

## C2
# sex
a = credit %>% 
  group_by(mayor, bias, sex) %>% 
  tally() %>% 
  mutate(variable = "sex") %>% 
  rename(group = sex)

# class
b = credit %>% 
  group_by(mayor, bias, poor) %>% 
  tally() %>% 
  mutate(poor = ifelse(poor == 1, "Lower class", "Upper/middle class"),
         variable = "class") %>% 
  rename(group = poor)

# party
c = credit %>% 
  group_by(mayor, bias, partisanship) %>% 
  tally() %>% 
  mutate(partisanship = recode(partisanship,
                               `1` = "Peronism",
                               `2` = "PRO",
                               `3` = "Other",
                               `4` = "Blank/null/did not vote",
                               .missing = "No answer"),
         variable = "partisanship") %>% 
  rename(group = partisanship)

# copartisanship
d = credit %>% 
  group_by(mayor, bias, partisan_match_control) %>% 
  tally() %>% 
  mutate(partisan_match_control = recode(partisan_match_control,
                                         `0` = "No",
                                         `1` = "Yes",
                                         .missing = "No answer"),
         variable = "copartisanship") %>% 
  rename(group = partisan_match_control)

# gender remember
e = credit %>% 
  mutate(recall_gender_misremember = ifelse(
    mayor == "Man mayor" & recall_gender == 2 |
      mayor == "Woman mayor" & recall_gender == 1,
    1, 0)) %>% 
  group_by(mayor, bias, recall_gender_misremember) %>% 
  tally() %>% 
  mutate(recall_gender_misremember = recode(recall_gender_misremember,
                                            `0` = "No",
                                            `1` = "Yes",
                                            .missing = "No answer"),
         variable = "misremember") %>% 
  rename(group = recall_gender_misremember)

# bind together
sizes = bind_rows(a, b, c, d, e) %>% relocate(group)

sizes
